import Mock from "mockjs";

// 存储验证码信息
const captchaStore = new Map();

// 生成随机4位验证码
function generateCaptcha() {
  return Mock.Random.string("0123456789", 4);
}

// 图形验证码
Mock.mock(/\/api\/captcha\/image/, "get", () => {
  const captchaId = Mock.Random.guid();
  const captchaText = generateCaptcha();

  // 存储验证码
  captchaStore.set(captchaId, captchaText);

  // 5分钟后删除验证码
  setTimeout(() => {
    captchaStore.delete(captchaId);
  }, 5 * 60 * 1000);

  return {
    code: 200,
    msg: "success",
    data: {
      captchaId: captchaId,
      captchaImg: Mock.Random.image("100x40", "#FFF", "#000", "png", captchaText),
    },
  };
});

// 短信验证码
Mock.mock(/\/api\/captcha\/sms/, "get", (options) => {
  const query = new URLSearchParams(options.url.split("?")[1]);
  const captchaId = query.get("captchaId");
  const captcha = query.get("captcha");

  // 验证图形验证码
  if (!captchaStore.has(captchaId)) {
    return {
      code: 400,
      msg: "验证码已过期，请重新获取",
    };
  }

  if (captchaStore.get(captchaId) !== captcha) {
    return {
      code: 400,
      msg: "图形验证码错误",
    };
  }

  // 验证成功后删除已使用的验证码
  captchaStore.delete(captchaId);

  return {
    code: 200,
    msg: "success",
    data: {
      smsKey: Mock.Random.guid(),
    },
  };
});

// 登录接口
Mock.mock(/\/api\/passport\/login/, "post", {
  code: 200,
  msg: "success",
  data: {
    token: "@guid",
    userInfo: {
      id: "@id",
      username: "@cname",
      avatar: "@image('100x100', '#FFF', '#000', 'png', 'avatar')",
      phone: /^1[3-9]\d{9}$/,
      "level|1-6": 1,
    },
  },
});
